import { reqGetPhoneCode, reqRegister, reqLogin,reqGetUserInfo,reqLogout } from "@/api";
import {getToken,setToken,deletToken} from '@/utils/set_token'

const state = {
  //手机验证码
  phoneCode: "",
  //用户token
  user_token:getToken('TOKEN'),
  //用户信息
  userInfo:{}
};

const mutations = {
  PHONECODE(store, data) {
    store.phoneCode = data;
  },
  USERDATE(store, data) {
    store.user_token = data;
  },
  USERINFO(store,data){
    store.userInfo = data;
  },
  CLEAR(store){
    store.userInfo = {};
    store.user_token = '';
    deletToken('TOKEN');
  }
};

const actions = {
  //验证码
  async reqGetPhoneCode({ commit }, phone) {
    const { data } = await reqGetPhoneCode(phone);
    if (data.code == 200) {
      commit("PHONECODE", data.data);
      return "ok";
    } else {
      return Promise.reject(new Error("fail"));
    }
  },
  //注册
  async reqUserRegister({ commit }, obj) {
    const { data } = await reqRegister(obj);
    if (data.code == 200) {
      return "ok";
    } else if (data.code == 223) {
      // code 223 表示已注册
      return "no";
    } else {
      return Promise.reject(new Error("fail"));
    }
  },
  //登录
  async reqLogin({ commit }, params) {
    const { data } = await reqLogin(params);
    if (data.code == 200) {
      commit("USERDATE", data.data.token);
      setToken('TOKEN',data.data.token)
      return "ok";
    } else {
      return Promise.reject(new Error(data.message));
    }
  },
  //退出登录
  async logout({commit}){
     const {data} = await reqLogout();
     if(data.code == 200){
       commit('CLEAR');
       return 'ok';
     }else{
       return Promise.reject(new Error('fail'))
     }
  },
  //获取用户信息
  async getUserInfo({commit}){
     const {data} = await reqGetUserInfo();
     if(data.code == 200){
        commit('USERINFO',data.data);
        return 'ok';
     }else{
        return Promise.reject(new Error('fail'));
     }
  }
};
const getters = {};

export default {
  state,
  mutations,
  actions,
  getters,
};
